package cn.com.twoke.app.pin_dou_dou.core;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONTokener;
import com.formdev.flatlaf.FlatDarkLaf;
import com.formdev.flatlaf.FlatLightLaf;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 设置对话框
 */
public class SettingsDialog extends JDialog {
    
    private JTextField workingDirField;
    private JComboBox<String> colorSchemeComboBox;
    private JComboBox<String> themeComboBox;
    private JCheckBox lockAspectRatioCheckBox;
    private JSpinner partitionWidthSpinner;
    private JSpinner partitionHeightSpinner;
    private JButton okButton;
    private JButton cancelButton;
    private JButton browseButton;
    
    // 用于存储所有可用的颜色方案名称
    private List<String> colorSchemes;
    // 用于存储所有可用的主题名称
    private List<String> themes;
    
    public SettingsDialog(Frame parent) {
        super(parent, "设置", true);
        initializeColorSchemes();
        initializeThemes();
        initComponents();
        layoutComponents();
        loadData();
        attachEventHandlers();
        pack();
        setLocationRelativeTo(parent);
    }
    
    /**
     * 初始化颜色方案列表
     */
    private void initializeColorSchemes() {
        colorSchemes = new ArrayList<>();
        try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("color-map.json")) {
            if (is != null) {
                JSONObject colorMap = new JSONObject(new JSONTokener(is, null));
                // 从第一个颜色条目中提取所有方案名称
                if (!colorMap.isEmpty()) {
                    JSONObject firstEntry = colorMap.getJSONObject(colorMap.keySet().iterator().next());
                    Set<String> schemeNames = firstEntry.keySet();
                    colorSchemes.addAll(schemeNames);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        // 如果没有找到任何方案，则添加默认方案
        if (colorSchemes.isEmpty()) {
            colorSchemes.add("MARD");
        }
    }
    
    /**
     * 初始化主题列表
     */
    private void initializeThemes() {
        themes = new ArrayList<>();
        themes.add("FlatLightLaf");
        themes.add("FlatDarkLaf");
    }
    
    /**
     * 初始化组件
     */
    private void initComponents() {
        workingDirField = new JTextField(20);
        colorSchemeComboBox = new JComboBox<>(colorSchemes.toArray(new String[0]));
        themeComboBox = new JComboBox<>(themes.toArray(new String[0]));
        lockAspectRatioCheckBox = new JCheckBox("锁定宽高比");
        // 创建分区宽度和高度的微调器
        partitionWidthSpinner = new JSpinner(new SpinnerNumberModel(Settings.getPartitionWidth(), 1, 1000, 1));
        partitionHeightSpinner = new JSpinner(new SpinnerNumberModel(Settings.getPartitionHeight(), 1, 1000, 1));
        okButton = new JButton("确定");
        cancelButton = new JButton("取消");
        browseButton = new JButton("浏览...");
    }
    
    /**
     * 布局组件
     */
    private void layoutComponents() {
        setLayout(new BorderLayout());
        
        // 创建主面板，并设置边距
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // 创建常规设置面板
        JPanel generalPanel = new JPanel(new GridBagLayout());
        generalPanel.setBorder(BorderFactory.createTitledBorder("常规设置"));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        
        // 工作目录标签和输入框
        gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 0;
        generalPanel.add(new JLabel("工作目录:"), gbc);
        
        gbc.gridx = 1; gbc.gridy = 0; gbc.weightx = 1.0;
        generalPanel.add(workingDirField, gbc);
        
        gbc.gridx = 2; gbc.gridy = 0; gbc.weightx = 0; gbc.fill = GridBagConstraints.NONE;
        generalPanel.add(browseButton, gbc);
        
        // 颜色方案标签和下拉框
        gbc.gridx = 0; gbc.gridy = 1; gbc.weightx = 0; gbc.fill = GridBagConstraints.HORIZONTAL;
        generalPanel.add(new JLabel("颜色方案:"), gbc);
        
        gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 2; gbc.weightx = 1.0;
        generalPanel.add(colorSchemeComboBox, gbc);
        
        // 主题标签和下拉框
        gbc.gridx = 0; gbc.gridy = 2; gbc.gridwidth = 1; gbc.weightx = 0; gbc.fill = GridBagConstraints.HORIZONTAL;
        generalPanel.add(new JLabel("主题:"), gbc);
        
        gbc.gridx = 1; gbc.gridy = 2; gbc.gridwidth = 2; gbc.weightx = 1.0;
        generalPanel.add(themeComboBox, gbc);
        
        // 创建图像设置面板
        JPanel imagePanel = new JPanel(new GridBagLayout());
        imagePanel.setBorder(BorderFactory.createTitledBorder("图像设置"));
        gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;
        
        // 锁定宽高比复选框
        gbc.gridx = 0; gbc.gridy = 0;
        imagePanel.add(lockAspectRatioCheckBox, gbc);
        
        // 分区宽度标签和微调器
        gbc.gridx = 0; gbc.gridy = 1; gbc.weightx = 0; gbc.fill = GridBagConstraints.HORIZONTAL;
        imagePanel.add(new JLabel("分区宽度(块):"), gbc);
        
        gbc.gridx = 1; gbc.gridy = 1; gbc.weightx = 1.0;
        imagePanel.add(partitionWidthSpinner, gbc);
        
        // 分区高度标签和微调器
        gbc.gridx = 0; gbc.gridy = 2; gbc.weightx = 0; gbc.fill = GridBagConstraints.HORIZONTAL;
        imagePanel.add(new JLabel("分区高度(块):"), gbc);
        
        gbc.gridx = 1; gbc.gridy = 2; gbc.weightx = 1.0;
        imagePanel.add(partitionHeightSpinner, gbc);
        
        // 将设置面板添加到主面板
        mainPanel.add(generalPanel, BorderLayout.NORTH);
        mainPanel.add(imagePanel, BorderLayout.CENTER);
        
        add(mainPanel, BorderLayout.CENTER);
        
        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
        buttonPanel.add(okButton);
        buttonPanel.add(cancelButton);
        add(buttonPanel, BorderLayout.SOUTH);
    }
    
    /**
     * 加载设置数据
     */
    private void loadData() {
        workingDirField.setText(Settings.getWorkingDir());
        String currentScheme = Settings.getColorScheme();
        colorSchemeComboBox.setSelectedItem(currentScheme);
        String currentTheme = Settings.getTheme();
        themeComboBox.setSelectedItem(currentTheme);
        lockAspectRatioCheckBox.setSelected(Settings.isLockAspectRatio());
        partitionWidthSpinner.setValue(Settings.getPartitionWidth());
        partitionHeightSpinner.setValue(Settings.getPartitionHeight());
    }
    
    /**
     * 附加事件处理器
     */
    private void attachEventHandlers() {
        // 浏览按钮事件
        browseButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                fileChooser.setDialogTitle("选择工作目录");
                
                String currentDir = workingDirField.getText();
                if (StrUtil.isNotBlank(currentDir)) {
                    fileChooser.setCurrentDirectory(new java.io.File(currentDir));
                }
                
                int result = fileChooser.showOpenDialog(SettingsDialog.this);
                if (result == JFileChooser.APPROVE_OPTION) {
                    workingDirField.setText(fileChooser.getSelectedFile().getAbsolutePath());
                }
            }
        });
        
        // 确定按钮事件
        okButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 保存设置
                Settings.setWorkingDir(workingDirField.getText());
                Settings.setColorScheme((String) colorSchemeComboBox.getSelectedItem());
                Settings.setTheme((String) themeComboBox.getSelectedItem());
                Settings.setLockAspectRatio(lockAspectRatioCheckBox.isSelected());
                Settings.setPartitionWidth((Integer) partitionWidthSpinner.getValue());
                Settings.setPartitionHeight((Integer) partitionHeightSpinner.getValue());
                Settings.save();
                
                // 关闭对话框
                dispose();
            }
        });
        
        // 取消按钮事件
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
    }
}